﻿var context;
var web;
var user;

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
    var data = {
        json: $.toJSON([
                {
                    "id": 1, "name": "one", "children": [
                       {
                           "id": 2, "name": "two", "children": [
                              { "id": 3, "name": "three", "children": [] },
                              { "id": 4, "name": "four", "children": [] }
                           ]
                       },
                       {
                           "id": 5, "name": "five", "children": [
                              { "id": 6, "name": "six", "children": [] },
                              { "id": 7, "name": "seven", "children": [] }
                           ]
                       }
                    ]
                },
                {
                    "id": 8, "name": "eight", "children": [
                       {
                           "id": 9, "name": "nine", "children": [
                              { "id": 10, "name": "ten", "children": [] },
                              { "id": 11, "name": "eleven", "children": [] }
                           ]
                       },
                       {
                           "id": 12, "name": "twelve", "children": [
                              { "id": 13, "name": "thirteen", "children": [] },
                              { "id": 14, "name": "fourteen", "children": [] }
                           ]
                       }
                    ]
                },
                { "id": 15, "name": "fifteen", "children": [] }
        ]),
        delay: 1
    }

    var ViewModel = function () {
        var self = this;
        self.initialized = ko.observable(false);
        self.items = ko.observableArray();

        // Use JSFiddle echo to simulate an AJAX service
        (function () {
            $.ajax({
                url: "/echo/json/", data: data, type: "POST",
                success: function (data) {
                    // Map the returned JSON to the View Model  
                    ko.mapping.fromJS(data, {}, self.items);
                    self.initialized(true);
                }
            });
        })();
    };

    ko.bindingHandlers.dynatree = {
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            setTimeout(function () { $(element).dynatree() }, 0);
        }
    };

    ko.applyBindings(new ViewModel());
});